const {
  getAddress, // 获取地址列表
  addAddress, // 确定添加地址
  editAddress, // 确认编辑地址
  deleteAddress, // 删除地址
} = require("../../../utils/request/Api/user");

Page({
  data: {
    addressArray: [],

    consignee: "", // 收货人
    area: "", // 所在地区
    address: "", // 详细地址
    phone: "", // 手机号码
  },
  onLoad() {
    getAddress().then((res) => {
      this.setData({
        addressArray: res,
      });
    });
  },

  /**
   * 获取当前点击项的数据
   * @param {*} e
   */
  getItemData(e) {
    const index = e.target.dataset.index;
    const item = this.data.addressArray[index];
    this.setData({
      id: item.id,
      consignee: item.consignee,
      area: item.area,
      address: item.address,
      phone: item.phone,
    });
  },

  /**
   * 确认编辑地址
   */
  confirmEdit(e) {
    const { type } = e.target.dataset;
    if (type == "add") {
      addAddress({
        consignee: this.data.consignee,
        area: this.data.area,
        address: this.data.address,
        phone: this.data.phone,
      }).then((res) => {
        wx.showToast({
          title: "添加成功",
          icon: "success",
          duration: 2000,
        });
        getAddress().then((res) => {
          this.setData({
            addressArray: res,
          });
        });
      });

      return;
    }

    wx.showModal({
      title: "提示",
      content: "是否确认修改",
      complete: (res) => {
        if (res.confirm) {
          editAddress({
            profile_id: this.data.id,
            consignee: this.data.consignee,
            area: this.data.area,
            address: this.data.address,
            phone: this.data.phone,
          }).then((res) => {
            wx.showToast({
              title: "修改成功",
              icon: "success",
              duration: 2000,
            });
            getAddress().then((res) => {
              this.setData({
                addressArray: res,
              });
            });
          });
        }
      },
    });
  },
  confirmDelete(e) {
    const { id } = e.target.dataset;
    wx.showModal({
      title: "提示",
      content: "是否确认删除",
      complete: (res) => {
        if (res.confirm) {
          deleteAddress({ profile_id: id }).then((res) => {
            wx.showToast({
              title: "删除成功",
              icon: "success",
              duration: 2000,
            });
            getAddress().then((res) => {
              this.setData({
                addressArray: res,
              });
            });
          });
        }
      },
    });
  },
});


